import '../libs/CSS2DRenderer';
import { EventListener } from "../libs/EventListener";

//
export function Labels(props = {}) {

    // type
    this.type = 'Labels';

    // sprite
    this.sprite = new THREE.Sprite(new THREE.SpriteMaterial({ transparent: true }));
    this.sprite.scale.set(0.0001, 0.0001, 0.0001);
    this.sprite.type = this.type;

    //
    this.divElement = document.createElement('div');
    this.divElement.className = "vr-panoramic-labels";

    // className
    if(props.className) {
        this.divElement.classList.add(props.className);
    }

    // content
    if (typeof props.content === 'object') {
        this.divElement.appendChild(props.content);
    }
    else if (typeof props.content === 'string') {
        this.divElement.innerHTML = props.content;
    }

    // add
    this.sprite.add(this.divObject = new THREE.CSS2DObject(this.divElement));


    // add to
    this.addTo = (parent) => {
        //
        this.parent = parent;
        //
        if (parent) parent.add(this.sprite);
        //
        return this;
    };

    // remove
    this.remove = () => {
        //
        this.sprite.geometry.dispose();
        this.sprite.material.dispose();
        //
        if (this.divElement.parentNode) {
            this.divElement.parentNode.removeChild(this.divElement);
        }
        //
        this.parent && this.parent.remove(this.sprite);
    }

    // show
    this.show = () => {
        this.divObject.visible = true;
        return this;
    }

    // show
    this.hide = () => {
        this.divObject.visible = false;
        return this;
    }

    // set coords
    this.setCoords = (x, y, z) => {

        if (x instanceof Array) {
            z = x[2];
            y = x[1];
            x = x[0];
        }
        else if (typeof x === 'object') {
            z = x.z;
            y = x.y;
            x = x.x;
        }
        //
        this.sprite.position.set(x, y, z);

        //
        return this;
    };

    // on click
    this.divElement.addEventListener('click', e => {
        //
        if (this._listeners?.click?.length) {
            // preventDefault
            e.preventDefault();
            e.stopPropagation();
            // emit
            this.emit('click', e);
        }
    }, false);

}

//
Labels.prototype = Object.assign(Labels.prototype, EventListener.prototype);
Labels.constructor.constructor = Labels;